package cn.org.donald.framework.util;
import cn.org.donald.framework.constant.EncodeConstant;
import cn.org.donald.framework.handler.ServiceException;
import cn.org.donald.framework.pojo.dto.LoginUser;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取request上下文工具类
 * @author ： Donald
 * @since  ： 2020/10/24 12:30
 *
 */
public class RequestUtil {

    /**
     * 获取user登录后的用户信息对象LoginUser
     * @param request HttpServletRequest
     * @return LoginUser
     */
    public static LoginUser getLoginUser(HttpServletRequest request){
        String authorization = getAuthorization(request);
        try {
            return (LoginUser) redisTemplate().opsForValue().get(authorization);
        }catch (Exception e){
            throw new ServiceException(HttpStatus.UNAUTHORIZED.value(),"登录超时,请重新登录");
        }
    }

    /**
     * 获取authorization Token
     * @param request
     * @return
     */
    public static String getAuthorization(HttpServletRequest request){
        return request.getHeader(EncodeConstant.AUTHORIZATION_NAME);
    }


    /**
     * 获取相对真实的ip地址
     * @param request
     * @return
     */
    public static String getRealIp(HttpServletRequest request){
        String ip = null;


        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;//本机ip地址则返回127.0.0.1

    }


    private static RedisTemplate redisTemplate(){
      return (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
    }


    /**
     * 获取登录用户的id
     * @param request
     * @return
     */
    public static Long getUserId(HttpServletRequest request) {
        try {
            String userId = request.getHeader("userId");
            return Long.parseLong(userId);
        }catch (Exception e){
            throw new UnauthenticatedException(e);
        }

    }
}
